import React, { PureComponent } from 'react';
import { Router, Switch, Route, Link, Redirect, withRouter } from 'dva/router';
import dynamic from 'dva/dynamic';
import { ActivityIndicator, Modal } from "antd-mobile"
import Main from "./layouts/Main"
import { connect } from "dva"
import { isNull, goToPage, loginCallbackToken, loadScript } from "./utils/helper"
import Error from "./routes/Error/Error"
import Index from "./routes/Index/Index"
import Create from "./routes/Form/Create"
import Edit from "./routes/Form/Edit"
import Login from "./routes/Login/Login"
import Map from "./routes/Map/Map"
import ChangePWD from "./routes/Login/ChangePassword"
import MToast from "./components/Util/MToast"
import { setLogout, getParmaFromUrl } from './utils/request';
import MelaShop from './routes/MelaOnline/MelaShop';
import NewLogin from './routes/MelaOnline/NewLogin';
import Category from './routes/MelaOnline/Category';
import GoodsDetail from './routes/MelaOnline/GoodsDetail';
import UnGoodCart from './routes/MelaOnline/UnGoodCart';
import GoodCart from './routes/MelaOnline/GoodCart';
import Way from './routes/MelaOnline/Way';
import PlaceOrder from './routes/MelaOnline/PlaceOrder';
import AddAddress from './routes/MelaOnline/AddAddress';
import AddressList from './routes/MelaOnline/AddressList';
import ModifyAddress from './routes/MelaOnline/ModifyAddress';
import My from './routes/MelaOnline/My';
import Chat from './routes/MelaOnline/chat';
import MyOrder from './routes/MelaOnline/MyOrder';
import orderDetail from './routes/MelaOnline/orderDetail';
import searchPage from './routes/MelaOnline/searchPage'
import categoryPage from './routes/MelaOnline/CategoryPage';
import categoryPage1 from './routes/MelaOnline/CategoryPage1';
import categoryPage2 from './routes/MelaOnline/CategoryPage2';
import PaySuccess from './routes/MelaOnline/PaySuccess';
import Cash from './routes/MelaOnline/Cash';
import FeedBack from './routes/MelaOnline/FeedBack';
import Register from './routes/Login/Register';

let allHomePath = [];
try {
	allHomePath = all_home_path
}
catch (e) {

}
//路由加载时的动画
dynamic.setDefaultLoadingComponent(() => {
	return <ActivityIndicator toast text="正在加载" animating={true} />;
});

@connect(() => {
	return ({})
})
class RouterContent extends PureComponent {
	constructor(props) {
		super(props);
		this.state = {
			showRouter: false,
			menuConfig: {}
		}
	}
	// 之前是调用接口获取menus信息  现在所有的信息都通过app传过来 不需要再另外调用接口
	h5Login = () => {
		let { dispatch } = this.props;
		dispatch({
			type: "login/login_h5",
			payload: {
				data: {
					token: localStorage[MI_APP_CODE + "mi_token"]
				},
				isCreateEdit: true,
				callback: (res) => {
					let { code, msg, data } = res;
					// console.log("login_h5",res);
					let { user, app, permissions, menus } = data;
					// user 为空
					if (code == 10200) {
						localStorage[MI_APP_CODE + "menus"] = JSON.stringify(menus);
						localStorage[MI_APP_CODE + "user_id"] = user.id || 1;
						localStorage[MI_APP_CODE + "role_id"] = user.role_id || 1;
						localStorage[MI_APP_CODE + "username"] = "Admin";
						localStorage[MI_APP_CODE + "permissions"] = permissions;
						// window.location.reload();
					}
					else {
						MToast.fail(msg)
					}
				}
			}
		});
	}

	componentDidMount() {
		if (browser.isInApp) {
			let callbackToken = (e) => {
				loginCallbackToken(e);
			}
			Func.getBridge(function (_bridge) {
				bridge = _bridge;
				Func.registerHanderBridge('callbackToken', callbackToken)
				//在这里去请求app的token
				if (!localStorage[MI_APP_CODE + "mi_token"]) {
					// Modal.alert("h5","token空");
					Func.callHander(bridge, "reqToken", {});
				}
				Func.registerHanderBridge("setLogout", setLogout);
			});
		}
	}
	componentWillMount() {
		let { history } = this.props;
		history.listen(props => {//监听路由变化,页面滚动到顶部
			let urlParams = getParmaFromUrl(window.location.href);
			let { hzl_username, hzl_mobile } = urlParams;
			if (!isNull(hzl_username) && !isNull(hzl_mobile)) {
				localStorage.setItem(MI_APP_CODE + "hzl_username", hzl_username)
				localStorage.setItem(MI_APP_CODE + "hzl_mobile", hzl_mobile)
			}
		})
		let { dispatch } = this.props;
		let mi_token = localStorage[MI_APP_CODE + "mi_token"];
		let location = window.location;
		let { hash } = location;
		if (hash && (hash.indexOf("/login") != -1 || hash.indexOf("/register") != -1)) {
			return;
		}
		else {

			let to_path = localStorage.getItem(MI_APP_CODE + "to_path");
			if (isNull(to_path)) {
				localStorage.setItem(MI_APP_CODE + "to_path", hash.substring(1));//第一次进来的页面,如果页面属于首页,登陆成功之后跳转到这个页面
				// if (allHomePath && allHomePath.length > 0) {
				// 	let is_home = false;
				// 	allHomePath.map(i => {
				// 		if (p.indexOf(i) == 0) {
				// 			is_home = true
				// 		}
				// 	})
				// 	if (is_home) {
				// 		localStorage.setItem(MI_APP_CODE+"to_path", hash.substring(1));//第一次进来的页面,如果页面属于首页,登陆成功之后跳转到这个页面
				// 	}
				// }
			}
			// alert(1);
			console.log("mi_token-componentWillMount", mi_token);
			if (isNull(mi_token)) {
				if (browser.isInApp) {
				}
				else {
					this.props.history.replace("/login");
				}
			}
			else {
				window.less = {
					async: true,
				};
				let isTransparent = false;
				try {
					isTransparent = mi_is_transparent
				}
				catch (e) {

				}
				if (isTransparent) {
					const link = document.createElement("link");
					link.href = "./assets/transparent_color.css";
					link.rel = "stylesheet";
					document.head.appendChild(link);
				}
				// loadScript("assets/less.min.js").then(() => {
				// 	let theme_color = "#1890ff";
				// 	window.less.modifyVars({
				// 		'@primary-color': theme_color,
				// 		"@background-color":"transparent",
				// 		"@text-color":"#fff"
				// 	});
				// 	// localStorage[MI_APP_CODE+"theme_color"] = theme_color;
				// })
				dispatch({
					type: "global/loadMenu",
					payload: {
						callback: (result) => {
							this.setState({
								showRouter: true,
								menuConfig: result
							})
						}
					}
				})
			}
		}
	}

	render() {
		let { history, app, dispatch } = this.props;
		let { showRouter, menuConfig } = this.state;
		let location = window.location;
		let { hash } = location;
		let isLogin = false;
		if (hash && (hash.indexOf("/login") != -1 || hash.indexOf("/register") != -1)) {
			isLogin = true;
		}
		if (!isLogin && !showRouter) {
			return null;
		}
		let { default_page, default_page_title, globalMenu = [] } = menuConfig;
		let defaultPath = default_page;
		globalMenu.map(item => {
			if (item.code == default_page) {
				defaultPath = item.path
			}
		});
		if (!isNull(defaultPath)) {
			if (hash.substring(1) === "/") {
				goToPage({
					dispatch, config: {
						url: defaultPath
					}, isReplace: true
				})
			}
		}
		let routerArr = {};
		routerArr["/"] = Index;
		routerArr["/create"] = Create;
		routerArr["/edit"] = Edit;
		routerArr["/login"] = Login;
		routerArr["/page"] = Create;
		routerArr["/map"] = Map;
		routerArr["/changePassword"] = ChangePWD;
    routerArr["/shop_home"] = MelaShop;
    routerArr["/newLogin"] = NewLogin;
    routerArr["/category"] = Category;
    routerArr["/goodcart"] = GoodCart;
    routerArr["/ungoodcart"] = UnGoodCart;
    routerArr["/way"] = Way;
    routerArr["/placeOrder"] = PlaceOrder;
    routerArr["/addAddress"] = AddAddress;
    routerArr["/addressList"] = AddressList;
    routerArr["/modifyAddress"] = ModifyAddress;
    routerArr["/goodsDetail"] = GoodsDetail;
    routerArr["/my"] = My;
    routerArr["/myOrder"] = MyOrder;
    routerArr["/orderDetail"] = orderDetail;
    routerArr["/searchPage"] = searchPage;
    routerArr["/category_page"] = categoryPage;
    routerArr["/category_page1"] = categoryPage1;
    routerArr["/category_page2"] = categoryPage2;
    routerArr["/chat"] = Chat;
		routerArr["/register"] = Register;
    routerArr["/cash"] = Cash;
    routerArr["/pay_success"] = PaySuccess;
    routerArr["/feedback"] = FeedBack;
		// routerArr["/"]       = dynamic({app,models:()=>[],component:() =>import('./routes/Index/Index')});
		// routerArr["/create"] = dynamic({app,models:()=>[],component:() =>import('./routes/Form/Create')});
		// routerArr["/edit"]   = dynamic({app,models:()=>[],component:() =>import('./routes/Form/Edit')});
		// routerArr["/login"]  = dynamic({app,models:()=>[],component: () =>import('./routes/Login/Login')});
		// routerArr["/page"]   = dynamic({app,models:()=>[],component: () =>import('./routes/Form/Create')});
		// routerArr["/map"]  = dynamic({app,models:()=>[],component: () =>import('./routes/Map/Map')});
		// routerArr["/changePassword"]  = dynamic({app,models:()=>[],component: () =>import('./routes/Login/ChangePassword')});
		// const Error          = dynamic({app,models:()=>[],component:() =>import('./routes/Error/Error')});

		let routers = [];
		for (let i in routerArr) {
			routers.push(
				<Route key={i} exact path={i} component={routerArr[i]} />
			)
		}
		return (
			<Router history={history}>
				<Route
					render={({ location }) => (
						<Main location={location} routerArr={routerArr} >
							{/* 添加key值，解决参数变化时页面不刷新的问题 key值变化 router就会重新渲染 比如 page?_c=a 变为 page?_c=b ，如果不做处理，页面就不会刷新*/}
							<Switch key={location.pathname + location.search}>
								{routers}
								<Route exact component={Error} />
							</Switch>
						</Main>
					)} />
			</Router>
		);
	}
}
function RouterConfig(props) {
	return (
		<RouterContent {...props} />
	);
}
export default RouterConfig;
